import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { FormattedMessage } from 'umi-plugin-react/locale';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from '@/components/PageLoading';
import { Card, Button, Icon, List, Modal, message, Avatar, Switch, Pagination } from 'antd';
import Ellipsis from '@/components/Ellipsis';
import styles from './index.less';
import del1Img from '@/assets/knowledge/del1.png';
import editImg from '@/assets/knowledge/edit.png';
import addImg from '@/assets/dialog/add.png';
import onImg from '@/assets/knowledge/on.png';
import offImg from '@/assets/knowledge/off.png';
import RobotBtn from '@/utils/robotBtn';
import Bottword from '@/modules/Bottword.js';
const AddDialog = React.lazy(() => import('./add'));
const confirm = Modal.confirm;
@connect(({ DialogList, loading }) => ({
  DialogList,
  loading: loading.models.data,
}))

class DialogList extends Component {
  state = {
    limit:14,
    page: 1,
    list:[],
    loading:true,
    total: 0,
    visible: false,
    pageSize:16
  };

  componentDidMount() {
    this.fetchList();
  };

  fetchList=()=>{
    const { dispatch } = this.props;
    const {limit,page} = this.state;
    dispatch({
      type: 'dialogList/fetchList',
      payload: {
        limit,page
      },
      callback:(res)=>{
        this.setState({
          total: res.total,
          list: res.data,
          loading: false
        })
      }
    });
  };

  delDialog=(id,name)=>{
    const { dispatch } = this.props;
    const  that = this;
    const title = '请问您是否删除【'+name+'】?';
    confirm({
      title: title,
      content: '',
      okText:"确定",
      cancelText:"取消",
      onOk() {
        dispatch({
          type: 'dialogList/delDialog',
          payload: {
            dialogId:id
          },
          callback:(res)=>{
            if(!res.code){
              message.info(res.msg);
              that.fetchList();
            }
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  };

  fixStatus=(id,type)=>{
    const { dispatch } = this.props;
    const  that = this;
    dispatch({
      type: 'dialogList/fixDialogStatus',
      payload: {
        dialogId:id,
        disabled:type
      },
      callback:(res)=>{
        if(!res.code){
          message.info(res.msg);
          that.fetchList();
        }
      }
    });
  };

  fenye=(page)=>{
    this.setState({
      page,
      loading:true
    },()=>{
      this.fetchList()
    })
  };

  addOrEditDialog=(id,name)=>{
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'dialogList/redirect',
        payload: {id,name},
      });
    });
  };

  onShowSizeChangeForPage=(current,size)=>{
    this.setState({
      limit:size,
      page:current
    },()=>{
      this.fetchList();
    })
  };

  addDialog=(name)=>{
    const { dispatch,currentUser } = this.props;
    const form = this.formRef.props.form;
    dispatch({
      type: 'dialogList/add',
      payload: {
        name,
        robotId:currentUser.robotId
      },
      callback:(res)=>{
        if(!res.code){
          this.fetchList();
          form.resetFields();
          message.info(res.msg)
          this.setState({ visible: false });
        }
      }
    });
  };

  showModal = () => {
    this.setState({ visible: true });
  };

  handleCancel = () => {
    this.setState({ visible: false });
  };

  handleCreate = () => {
    const form = this.formRef.props.form;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      this.addDialog(values.name);
    });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };


  render() {
    const {
      list,
      loading,
      total,limit
    } = this.state;
    function Checking(props) {
      const status = props.status;
      switch (status) {
        case 1:
          return (
            <span style={{color:'grey',marginLeft:10}}><Icon type="loading" />训练中</span>
          );
        case 4:
          return (
            <span style={{color:'grey',marginLeft:10}}><Icon type="stop" />训练异常</span>
          );
        default:
          return '';
      }
    }
    return (
      <GridContent>
        <Suspense fallback={<PageLoading />}>
            <div className={styles.cardList}>
              <p className={styles.pageTitle}>对话工坊</p>
              <div style={{height:'calc(100vh - 150px)',overflowY:'auto',overflowX:'hidden'}}>
                <List
                       rowKey="id"
                       loading={loading}
                  // pagination={{
                  //   onChange: page => {
                  //    this.fenye(page)
                  //   },
                  //   pageSize: 16,
                  //   total,
                  //   showQuickJumper: true,
                  // }}
                       grid={{ gutter: 24, lg: 3,  sm: 2, xs: 1 }}
                       dataSource={['',...list]}
                       renderItem={item =>
                         item ? (
                           <List.Item key={item._id}>
                             <Card hoverable className={styles.card} actions={[]}>
                               <Card.Meta
                                 avatar={<Avatar className={styles.cardAvatar}>{item.name.substr(0,1)} </Avatar>}
                                 // title={<a>{item.name}</a>}
                                 // description={
                                 //   <Ellipsis className={styles.item} lines={3}>
                                 //     {/*{*/}
                                 //     {/*  item.disabled?*/}
                                 //     {/*  <span style={{color:'red'}}><Icon type="pause-circle" className={styles.icon} />已停用</span>*/}
                                 //     {/*  :*/}
                                 //     {/*  <span style={{color:'skyblue'}}><Icon type="play-circle" className={styles.icon} />启用中</span>*/}
                                 //     {/*}*/}
                                 //     <Checking status={item.status} />
                                 //   </Ellipsis>
                                 // }
                               />
                               <div className={styles.cardHead}>
                                 {
                                   item.disabled?
                                     <div>
                                       {
                                         item.status ===1?
                                           <div>
                                             <span style={{color:'#4a4a4a',fontSize:'16px',}}>{item.name}</span>
                                             <Ellipsis className={styles.item} lines={3}>
                                               <Checking status={item.status} />
                                             </Ellipsis>
                                           </div>
                                           :
                                           <span>
                                           {item.name}
                                        </span>
                                       }
                                     </div>
                                     :
                                     <span >{item.name}</span>
                                 }
                               </div>
                               <div className={styles.cardTool}>
                                 <img src={editImg} alt="编辑知识点" style={{marginRight:5,cursor:"pointer"}} onClick={() => this.addOrEditDialog(item._id,item.name)}  />
                                 <img src={del1Img} alt="删除知识点" style={{marginRight:5,cursor:"pointer"}} onClick={() => this.delDialog(item._id,item.name)} />
                                 {
                                   item.disabled?
                                     <img src={offImg} style={{cursor:"pointer",width:30,marginTop:5}} alt="" onClick={()=>this.fixStatus(item._id,false)} />
                                     :
                                     <img src={onImg} style={{cursor:"pointer",width:30,marginTop:5}} alt="" onClick={()=>this.fixStatus(item._id,true)} />
                                 }
                               </div>
                             </Card>
                           </List.Item>
                         ) : (
                           <List.Item>
                             {/*<div  className={styles.newButton} onClick={()=>this.showModal()}>*/}
                             {/*  <Icon type="plus" /> 新建多轮会话*/}
                             {/*</div>*/}
                             <div className={styles.addButton}  onClick={()=>this.showModal()}>
                               <img  src={addImg}/>
                             </div>
                           </List.Item>
                         )
                       }
                />
                <Pagination
                  style={{ textAlign: 'center', marginTop: 20}}
                  total={this.state.total}
                  current={this.state.page} // 当前页
                  showSizeChanger={true} // 是否显示可以设置几条一页的选项
                  onChange={this.fenye}
                  onShowSizeChange={(current, size) => this.onShowSizeChangeForPage(current, size)}
                  showTotal={() => `共 ${this.state.total} 条`}
                />

              </div>


              <AddDialog
                wrappedComponentRef={this.saveFormRef}
                visible={this.state.visible}
                onCancel={this.handleCancel}
                onCreate={this.handleCreate}
              />
            </div>

        </Suspense>
      </GridContent>
    );
  }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(DialogList);
